import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getUserImg } from '@/api/user'

const state = {
  // 发挥cookie长期存储的作用
  token: getToken(),
  userInfo: {},
  avatar: require('@/assets/common/bigUserHeader.png')
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步cookie数据变化
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    // 清除cookie数据
    removeToken()
  },
  // 请求用户数据
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  // 请求头像
  setUserAvatar(state, img) {
    state.avatar = img
  }
}
const actions = {
  async login(user, data) {
    const token = await login(data)
    // 响应拦截器把响应数据做了处理，错误响应不会进来
    user.commit('setToken', token)
    return true
  },
  // 首页获取用户信息-基于token
  async setUserInfo(user) {
    const userInfo = await getUserInfo()
    const userObj = await getUserImg(userInfo.userId)
    const obj = { ...userInfo, ...userObj }
    user.commit('setUserInfo', obj)
    user.commit('setUserAvatar', userObj.staffPhoto)
  },
  logout(user) {
    user.commit('removeToken')
    user.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
